package com.hanthink.system.service.impl.pc;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.StringUtils;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.pc.EmItemFile;
import com.hanthink.system.domain.pc.EmJobItem;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.EmItemFileMapper;
import com.hanthink.system.mapper.EmJobItemMapper;
import com.hanthink.system.service.ISysDeptService;
import com.hanthink.system.service.impl.SysUserServiceImpl;
import com.hanthink.system.service.pc.IEmJobItemService;

/**
 * 设备点检项Service业务层处理
 * 
 * @author hanthink
 * @date 2021-01-27
 */
@Service
public class EmJobItemServiceImpl implements IEmJobItemService {
	private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
	@Autowired
	private EmJobItemMapper emJobItemMapper;

	@Autowired
	private EmItemFileMapper emItemFileMapper;

	@Autowired
	private ISysDeptService deptService;

	@Autowired
	private EmEquipMapper emEquipMapper;

	/**
	 * 查询设备点检项
	 * 
	 * @param id 设备点检项ID
	 * @return 设备点检项
	 */
	@Override
	public EmJobItem selectEmJobItemById(Long id) {
		return emJobItemMapper.selectEmJobItemById(id);
	}

	/**
	 * 查询设备点检项列表
	 * 
	 * @param emJobItem 设备点检项
	 * @return 设备点检项
	 */
	@Override
	public List<EmJobItem> selectEmJobItemList(EmJobItem emJobItem) {
		return emJobItemMapper.selectEmJobItemList(emJobItem);
	}

	/**
	 * LPA三级以上任务查询
	 * @return
	 */
	@Override
	public List<EmJobItem> selectEmJobItemListLPA() {
		return emJobItemMapper.selectEmJobItemListLPA();
	}

	/**
	 * 新增设备点检项
	 * 
	 * @param emJobItem 设备点检项
	 * @return 结果
	 */
	@Override
	public int insertEmJobItem(EmJobItem emJobItem) {
		// 校验在系统中是否存在
		EmJobItem queryEmJobItem = new EmJobItem();
		queryEmJobItem.setSiteKey(emJobItem.getSiteKey());
		queryEmJobItem.setItemCode(emJobItem.getItemCode());
		List<EmJobItem> emJobItemList = emJobItemMapper.selectEmJobItemList(emJobItem);
		if (emJobItemList.size() > 0) {
			throw new CustomException("设备点检项:" + emJobItem.getItemCode() + "在系统中已存在，请核实");
		}
		// 校验设备是否存在
		EmEquip queryEmEquip = new EmEquip();
		queryEmEquip.setName(emJobItem.getEqKey());
		List<EmEquip> equipList = emEquipMapper.selectEmEquipList(queryEmEquip);
		if (equipList.size() == 0) {
			throw new CustomException("设备条码:" + emJobItem.getEqKey() + "在系统中不存在，请核实");
		}
		return emJobItemMapper.insertEmJobItem(emJobItem);
	}

	/**
	 * 修改设备点检项
	 * 
	 * @param emJobItem 设备点检项
	 * @return 结果
	 */
	@Override
	public int updateEmJobItem(EmJobItem emJobItem) {
		emJobItemMapper.updateEmTaskItem(emJobItem);
		return emJobItemMapper.updateEmJobItem(emJobItem);
	}

	/**
	 * 批量删除设备点检项
	 * 
	 * @param ids 需要删除的设备点检项ID
	 * @return 结果
	 */
	@Override
	public int deleteEmJobItemByIds(Long[] ids) {
		for (Long id : ids) {
//			EmJobItem dictType = selectEmJobItemById(id);
			EmItemFile emItemFile = new EmItemFile();
			emItemFile.setItemId(id);
			List<EmItemFile> list = emItemFileMapper.selectEmItemFileList(emItemFile);
			if (list.size() > 0) {
				for (EmItemFile file : list) {
					emItemFileMapper.deleteEmItemFileById(file.getId());
				}
			}
//			if (emItemFileMapper.countImageById(dictType.getId()) > 0) {
//				throw new CustomException(String.format("%1$s已存在点检文件不能删除", dictType.getItemCode()));
//			}
		}
		return emJobItemMapper.deleteEmJobItemByIds(ids);
	}

	/**
	 * 删除设备点检项信息
	 * 
	 * @param id 设备点检项ID
	 * @return 结果
	 */
	@Override
	public int deleteEmJobItemById(Long id) {
		return emJobItemMapper.deleteEmJobItemById(id);
	}

	/**
	 * 导入数据
	 * 
	 * @param jobitemList     数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @param operName        操作用户
	 * @return 结果
	 */
	@Override
	public String importJobitem(List<EmJobItem> jobitemList, Boolean isUpdateSupport, String operName) {
		if (StringUtils.isNull(jobitemList) || jobitemList.size() == 0) {
			throw new CustomException("导入设备点检项数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		int currentRowNum = 0;
		for (EmJobItem emJobItem : jobitemList) {
			if(StringUtils.isNotNull(emJobItem.getFilePath())) {
				emJobItem.setFilePath(emJobItem.getFilePath().trim());
			}
			currentRowNum++;
			try {
				// 事业部匹配
				SysDept hangame = new SysDept();
				hangame.setDeptName(emJobItem.getHangameKey());
				List<SysDept> hangameList = deptService.selectDeptList(hangame);
				if (hangameList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据事业部信息在系统中不存在，请核实");
					continue;
				}
				emJobItem.setHangameKey(hangameList.get(0).getDeptId().toString());
				
				// 工厂匹配
				SysDept dept = new SysDept();
				dept.setParentId(hangameList.get(0).getDeptId());
				dept.setDeptName(emJobItem.getSiteKey());
				List<SysDept> deptList = deptService.selectDeptList(dept);
				if (deptList.size() == 0) {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据工厂信息在事业部中不存在，请核实");
					continue;
				}
				emJobItem.setSiteKey(deptList.get(0).getDeptId().toString());
	
				List<EmJobItem> items = emJobItemMapper.selectEmJobItemByCode(emJobItem.getItemCode());
				if (items.size() > 0) {
					EmJobItem p = items.get(0);
					if (StringUtils.isNull(p)) {
						emJobItem.setCreateBy(operName);
						this.insertEmJobItem(emJobItem);
						successNum++;
						successMsg.append("<br/>" + successNum + "、设备点检项" + emJobItem.getItemCode() + " 导入成功");
					} else if (isUpdateSupport) {
						emJobItem.setUpdateBy(operName);
						emJobItem.setId(p.getId());
						this.updateEmJobItem(emJobItem);
						successNum++;
						successMsg.append("<br/>" + successNum + "、设备点检项 " + emJobItem.getItemCode() + " 更新成功");
						continue;
					} else {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、设备点检项 " + emJobItem.getItemCode() + " 已存在");
						continue;
					}
				} else {
					// 校验数据信息
					if (StringUtils.isEmpty(emJobItem.getSiteKey())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据 工厂不能为空");
						continue;
					} else if (StringUtils.isEmpty(emJobItem.getItemCode())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据点检项编码不能为空");
						continue;
					} else if (StringUtils.isNull(emJobItem.getItemDesc())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据点检项名称不能为空");
						continue;
					} else if (StringUtils.isEmpty(emJobItem.getEqKey())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据设备编码不能为空");
						continue;
					} else if (StringUtils.isEmpty(emJobItem.getExecuteMeans())
							|| !StringUtils.isNumeric(emJobItem.getExecuteMeans())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据执行方法不能为空且只能数字类型");
						continue;
					} else if (StringUtils.isNull(emJobItem.getCycle())
							|| !StringUtils.isNumeric(emJobItem.getCycle().toString())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据周期不能为空且只能数字类型");
						continue;
					} else if (StringUtils.isNull(emJobItem.getItemType())
							|| !StringUtils.isNumeric(emJobItem.getItemType())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据项目类型不能为空且只能数字类型");
						continue;
					} else if (StringUtils.isNull(emJobItem.getStatus())
							|| !StringUtils.isNumeric(emJobItem.getStatus())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据状态不能为空且只能数字类型");
						continue;
					} else if (StringUtils.isNull(emJobItem.getSortNum())
							|| !StringUtils.isNumeric(emJobItem.getSortNum().toString())) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据顺序不能为空且只能数字类型");
						continue;
					}

					// 校验
					List<EmJobItem> list = emJobItemMapper.selectEmJobItemByCode(emJobItem.getItemCode());
					if (list.size() != 0) {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、第" + currentRowNum + "行数据点检项信息在系统中已存在，请核实");
						continue;
					}

					emJobItem.setCreateBy(operName);
					this.insertEmJobItem(emJobItem);
					successNum++;
					successMsg.append("<br/>" + successNum + "、设备点检项 " + emJobItem.getItemCode() + " 导入成功");
				}

			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、设备点检项" + emJobItem.getItemCode() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
}
